<%@page import="java.util.HashMap"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%@ page import="java.util.ArrayList"%>
<%@ page import="java.util.HashSet"%>
<%@ page import="java.text.DecimalFormat"%>
<%@ page import="com.storyroad.responseClasses.StoryView"%>
<%@ page import="com.storyroad.responseClasses.Story"%>
<%@ page import="com.storyroad.responseClasses.Comment"%>
<%@ page import="com.storyroad.responseClasses.StoryLinkObject"%>

<%
	Story storyObject = (Story) request.getAttribute("storyObject");
	ArrayList<StoryLinkObject> stories = storyObject.getStoryLinks();
	HashMap<Integer, Integer> countMap = new HashMap<Integer, Integer>();
	getLevels(countMap, stories);
%>

<%!private void getLevels(HashMap<Integer, Integer> countMap,
			ArrayList<StoryLinkObject> stories) {
		
		countMap.put(stories.get(0).getStory_id(), 0);
		int headId = stories.get(0).getStory_id();
		for(int i=1;i<stories.size();i++){
			int currentParent = stories.get(i).getParent_id();
			int currentId = stories.get(i).getStory_id();
			countMap.put(currentId, countMap.get(currentParent)+1);
		}
	}%>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="shortcut icon" href="bootstrap/assets/ico/favicon.png">
    <script src="bootstrap/assets/js/jquery.js"></script>
    <script src="bootstrap/dist/js/bootstrap.min.js"></script>
    <script src="js/gen_validatorv4.js" type="text/javascript"></script>

    <script type="text/javascript" src="js/rating.js"></script>
    <title>View Story</title>

    <!-- Bootstrap core CSS -->
    <link href="bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <script>
        var map;
        var browserSupportFlag = new Boolean();
        /* Now sets the current locaiton as map center.
         * WE can modify it like if the current radio button is chosen,
         * Send the current location as form element, else use the marker.
         */
        function initialize() {
            var mapOptions = {
                zoom: 10,
                center: new google.maps.LatLng(11.100, 28.944),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById('map-canvas'),
                mapOptions);


            <%
            for (StoryLinkObject linkObject: storyObject.getStoryLinks()) {
                int currentId = linkObject.getStory_id();
                double x = storyObject.getStoryCoordinateMap().get(currentId).getX();
                double y = storyObject.getStoryCoordinateMap().get(currentId).getY(); %>
                lat = ( <%= String.valueOf(x) %> );
                long = ( <%= String.valueOf(y) %> );
                centerPoint = new google.maps.LatLng(lat, long);
                isCenter = false; <%
                if (currentId == storyObject.getS_id()) { %>
                        map.setCenter(centerPoint);
                    isCenter = true; <%
                } %>
                	var content = '<h4>' + "<%out.print(storyObject.getLocation());%>" +'</h4>';
                    placeMarker(centerPoint, isCenter, content); <%
            } %>

        }

        function placeMarker(location, isCenter, contentString) {
            var marker = new google.maps.Marker({
                position: location,
                map: map
            });
            if (!isCenter) {
                marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png');
            }
            else{
            	infowindow = new google.maps.InfoWindow({
                    content: contentString
                });
               
                google.maps.event.addListener(marker, 'click', function() {
                    infowindow.open(map,marker);
                  });
            }
        }

        google.maps.event.addDomListener(window, 'load', initialize);
    </script>

    <!-- Custom styles for this template -->
    <link href="css/viewstory.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="js/rating.css" />
    <script type="text/javascript">
        function disableRating() {
            $('#star-rating').unbind('mouseenter mouseleave');
            $('.star').unbind('mouseenter mouseleave');
            $('.star').off('click');
            $('#star-rating').rating.hover = null;
            $('.star').rating.hover = null;
            $('#star-rating').rating.click = null;
            $('.star').rating.click = null;
        }

        $(document)
            .ready(
                function () {
                    $(function () { // Start when document ready
                        $('#star-rating').rating(); // Call the rating plugin
                        $('#star-rating').rating.set(null, parseInt( <% out.print(storyObject.getMyRating()); %> ));
                    }); <%
                    if (storyObject.getMyRating() > 0) { %>
                            $('#star-rating').rating.set(null, parseInt( <% out.print(storyObject.getMyRating()); %> ));
                        disableRating(); <%
                    } %>
                        $(function () {
                            $('#star-rating')
                                .rating(
                                    function (vote, event) {
                                        // we have vote and event variables now, lets send vote to server.
                                        $.ajax({
                                            url: "RateStory",
                                            type: "GET",
                                            data: {
                                                rating: vote,
                                                story_id: <% out.print(request.getParameter(
                                                    "story_id")); %>
                                            },
                                            success: function (result) {
                                                if (result["rateSuccess"]) {
                                                    var rating = <% out.print(storyObject.getTotalRating()); %>
                                                        rating = parseInt(rating) + parseInt(vote);
                                                    var count = <% out.print(storyObject.getRatingCount()); %>
                                                        count = count + 1;
                                                    var newRating = (parseInt(rating) * 1.0 /
                                                        parseInt(count)).toFixed(1);
                                                    document.getElementById("rate").innerHTML =
                                                        newRating;
                                                    disableRating();
                                                }
                                            }
                                        });
                                    });
                        });
                });
    </script>


</head>

<body background="img/back_nologo.png">
    <div class="navbar navbar-fixed-top navbar-inverse" role="navigation">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>  <span class="icon-bar"></span>  <span class="icon-bar"></span>
                </button>
                <img src="img/logo_writing.png" id="top_logo">
            </div>
            <div class="collapse navbar-collapse">
                <ul class="nav navbar-nav">
                    <li class="active"><a href="MainPage">Home Page</a>
                    </li>
                    <li><a href="GetRecommendations">Recommendations</a>
                    </li>
                    <li><a href="Search.jsp">Search Stories</a>
                    </li>
                    <li><a href="GetFollowers">Following</a>
                    </li>
                </ul>
                <ul class="nav navbar-nav" id="profile_buttons">
                    <li><a href="GetProfile">My Profile</a>
                    </li>
                    <li><a href="Logout">Logout</a>
                    </li>
                </ul>
            </div>
            <!-- /.nav-collapse -->
        </div>
        <!-- /.container -->
    </div>
    <!-- /.navbar -->

    <div class="container">
        <div class="row">
            <div class="col-lg-6" id="sidebar">
                <div class="well sidebar-nav" id="view-page-container">
                    <h3 id="story-header">
						<%
							out.print(storyObject.getTitle());
						%>
					</h3>
                    <div id="profile-img">
                        <img src="<%out.print(storyObject.getPhotoLink());%>" alt="Profile Photo" height="100" width="100">
                        <a href="GetProfile?targetname=<%out.print(storyObject.getUserName());%>">
                            <center>
                                <% out.print(storyObject.getUserName()); %>
                            </center>
                        </a>
                    </div>
                    <div id="story-body">
                        <%for(StoryLinkObject storyLinkObject : storyObject.getStoryLinks()){ 
                        	int margin = countMap.get(storyLinkObject.getStory_id())*2;
                        %>
                            <div class="panel-group" id="accordion" style="padding-right:2%;margin-left:<%out.print(margin);%>%">
                                <div class="panel panel-default">
                                    <div class="panel-heading">
                                        <h4 class="panel-title">
						        <a data-toggle="collapse" data-parent="#accordion" href="#collapse<%out.print(storyLinkObject.getStory_id());%>">
						        <b>
						        	<%for(int i=0;i<countMap.get(storyLinkObject.getStory_id());i++){
						        		out.print("&nbsp&nbsp");out.print(">");} %>
						          <%out.print(storyObject.getStoryTitleMap().get(storyLinkObject.getStory_id())+" ("+
						        		  storyObject.getStoryUserMap().get(storyLinkObject.getStory_id())+")"); %>
						        </b>
						        </a>
						      </h4>
                                    </div>
                                    <div id="collapse<%out.print(storyLinkObject.getStory_id());%>" 
                                    class="panel-collapse collapse<% if(storyLinkObject.getStory_id() == storyObject.getS_id()) out.print(" in");%>">
                                        <div style="white-space:pre-line;padding-top:0%" class="panel-body">
                                            <%out.print(storyObject.getStoryBodyMap().get(storyLinkObject.getStory_id())); %>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <%} %>
                    </div>
                    <p id="tags">
                        <% out.print(storyObject.getTags()); %>
                    </p>
                    <hr>
                    <font size="5">Rating : </font><font id="rate"> <%
 	DecimalFormat numberFormat = new DecimalFormat("#.#");
  	out.print(numberFormat.format((storyObject.getTotalRating() * 1.0)
  			/ storyObject.getRatingCount()));
 %>
					</font>
                    <% if(request.getSession().getAttribute( "username")!=null){ %>
                        <div style="float: right">
                            <p>
                                <b>Click to rate:</b>
                                <div id="star-rating" style="margin: 10px">
                                    <input type="radio" name="example" class="rating" value="1" />
                                    <input type="radio" name="example" class="rating" value="2" />
                                    <input type="radio" name="example" class="rating" value="3" />
                                    <input type="radio" name="example" class="rating" value="4" />
                                    <input type="radio" name="example" class="rating" value="5" />
                                    <input type="radio" name="example" class="rating" value="6" />
                                    <input type="radio" name="example" class="rating" value="7" />
                                    <input type="radio" name="example" class="rating" value="8" />
                                    <input type="radio" name="example" class="rating" value="9" />
                                    <input type="radio" name="example" class="rating" value="10" />
                                </div>
                            </p>
                        </div>
                        <% } %>
                            <div style="float: right">
                                <p>
                                    <button type="button" class="btn btn-danger btn-xs" style="margin-left: 167px" onclick="window.location='ReportStory?story_id=<%out.print(storyObject.getS_id()); %>'">Inappropriate Content !</button>
                                </p>
                                <% if((request.getSession().getAttribute( "username")!=null && request.getSession().getAttribute( "username").equals(storyObject.getUserName()))||
                                storyObject.getAllowedList()!=null && !storyObject.getAllowedList().isEmpty() &&
                                request.getSession().getAttribute( "username")!=null && (storyObject.getAllowedList().equals(
                                "public")||storyObject.getAllowedList().contains((String)request.getSession().getAttribute(
                                "username")))){ %>
                                    <p>
                                        Write your story and link to this one...
                                        <button type="button" class="btn btn-warning btn-xs" onclick="window.location='CreateStory.jsp?parent_id=<%out.print(storyObject.getS_id());%>'">
                                            Link Story
                                        </button>
                                    </p>
                                    <% } %>
                            </div>

                            <% if(request.getSession().getAttribute("username")!=null){ %>
                                <p>
                                    <form action="AddComment" method="POST" id="comment_form">
                                        <textarea class="form-control" name="comment_body" id="comment-area" rows="3" placeholder="Write your comment here..."></textarea>
                                        <input type="hidden" name="story_id" value="<%out.print(storyObject.getS_id());%>">
                                        <input type="hidden" name="username" value="<%out.print(request.getSession().getAttribute(" username "));%>">
                                        <button type=submit class="btn btn-info btn-xs" id="share-button">Share</button>
                                </p>
                                </form>
                                <script type="text/javascript">
                                    var frmvalidator = new Validator("comment_form");
                                    frmvalidator
                                        .addValidation("comment-area", "req",
                                            "You cannot create an empty comment.");
                                    frmvalidator
                                        .addValidation("comment-area", "maxlen=140",
                                            "Your comment cannot be longer than 140 characters.");
                                </script>
                                <% } %>
                                    <div id="comments-scrollbar">
                                        <% ArrayList<Comment>comments = storyObject.getComments(); if (comments != null) { for (int
                                            i = 0; i
                                            < comments.size(); i++) { Comment comment= comments.get(i); %>
                                                <p id="comment-owner">
                                                    <% out.print(comment.getUsername() + " says: "); %>
                                                </p>
                                                <p id="comment-body">
                                                    <% out.print(comment.getBody()); %>
                                                </p>
                                                <p id="comment-date">
                                                    <% out.print(comment.getDate()); %>
                                                </p>
                                                <hr>
                                                <% } } %>
                                    </div>
                                    <!-- /.comments-scrollbar -->
                </div>
                <!-- /.well sidebar-nav -->

            </div>

            <!-- /.col-lg-6 -->
            <div id="map-canvas"></div>
            <div class="row">
            <% if(storyObject.getMedia().contains("imgur")){ %>
            <img src="<%out.print(storyObject.getMedia()); %>" style="height: 44%;width: 44%;margin-left: 3%;margin-top: 3%;">
            <%} %>
                <div class="col-xs-6 col-sm-3 sidebar-offcanvas" id="sidebar" role="navigation" style="width:24%; margin-left:2%">
                    <div class="well sidebar-nav" id="main-page-list-container">
                        <ul class="nav" id="main-page-list">
                            <li id="mainpagelistheader">Linked Stories</li>
                            <% for(StoryLinkObject linkedFragment : storyObject.getStoryLinks()){ %>
                                <li id="mainpagelist" class="active">
                                    <a href="ReadStory?story_id=<% out.print(String.valueOf(linkedFragment.getStory_id())); %>&request_type=Web">
                                        <% out.print(storyObject.getStoryTitleMap().get(linkedFragment.getStory_id())); %>
                                    </a>
                                </li>
                                <% } %>
                        </ul>
                    </div>
                    <!--/.well -->
                </div>
                <!--/span-->
                <div class="col-xs-6 col-sm-3 sidebar-offcanvas" id="sidebar" role="navigation" style="width:22%;margin-top:.4%">
                    <div class="well sidebar-nav" id="main-page-list-container">
                        <ul class="nav" id="main-page-list">
                            <li id="mainpagelistheader">Contributed Users</li>
                            <%HashSet<String>users = new HashSet
                                <String>(); for(StoryLinkObject linkedFragment2 : storyObject.getStoryLinks()){ 
                                	if(!users.contains(storyObject.getStoryUserMap().get(linkedFragment2.getStory_id()))){%>
                                    <li id="mainpagelist" class="active">
                                        <a href="GetProfile?targetname=<% out.print(storyObject.getStoryUserMap().get(linkedFragment2.getStory_id())); %>">
                                            <% out.print(storyObject.getStoryUserMap().get(linkedFragment2.getStory_id())); %>
                                        </a>
                                    </li>
                                    <% users.add(storyObject.getStoryUserMap().get(linkedFragment2.getStory_id())); }} %>
                        </ul>
                    </div>
                    <!--/.well -->
                </div>
                <!--/span-->
            </div>

        </div>

        <!-- /.row -->
    </div>
    <!-- /.container -->

    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="bootstrap/dist/js/bootstrap.min.js"></script>
</body>

</html>
